//
//  SearchViewController.m
//  网络FM
//
//  Created by dengzhicheng on 15/5/21.
//  Copyright (c) 2015年 dengzhicheng.com. All rights reserved.
//
#import "ShowImageCell.h"
#import "CircleLayout.h"
#import "SearchViewController.h"
#define KCellIdentifier @"identifier"
#import "SearchSecondCollectionViewCell.h"
#import "ChoiceButton.h"
#import "AnchorBurron.h"
#import "AnchorViewController.h"
 //跳转
#import "FeelingViewController.h"

#import <AFNetworking.h>


#import <UIImageView+WebCache.h>


#import "Cover.h"
#import "Anchor.h"


#import "SearchByChooseViewController.h"




@interface SearchViewController ()<UISearchBarDelegate>

@property (nonatomic,retain)NSArray *choiceArray;




@end

@implementation SearchViewController


- (void)dealloc
{
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.coverArray = [NSMutableArray array];
        self.anchorArray = [NSMutableArray array];
        self.automaticallyAdjustsScrollViewInsets = NO;
        //self.choice = [NSArray array];
            self.choiceArray = [[NSMutableArray alloc]initWithObjects:@"烦躁",@"悲伤", @"孤独", @"已弃疗",@"减压",@"无奈",@"快乐",@"感动",@"迷茫",@"睡前",@"旅行",@"散步",@"坐车",@"独处",@"失恋",@"失眠",@"随便", @"无聊",nil];
        //,@"睡前",@"旅行",@"散步",@"坐车",@"独处",@"失恋",@"失眠",@"随便", @"无聊"
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self createSearchBar];

    
}

- (void)viewDidLoad {
    [super loadView];
    [self createCollectionView];
    [self createScrollView];
    [self createGroupLable];
    [self createMybutton];

    [self SearchConnetion];
 
    self.navigationController.navigationBar.translucent = NO;
    
}



- (void)createCollectionView
{
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;

    
    
    self.collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, width, height)
                                      collectionViewLayout:[[CircleLayout alloc] init]];
    
    [self.collect registerClass:[ShowImageCell class] forCellWithReuseIdentifier:KCellIdentifier];
    [self.collect setBackgroundColor:[UIColor grayColor]];
    self.collect.delegate  =self;
    self.collect.dataSource = self;
    self.collect.pagingEnabled = YES;
    [self.collect setContentOffset:CGPointMake(self.view.frame.size.width, 0)];
    [self.view addSubview:self.collect];
    [self.collect release];
    
}




#pragma mark - UICollectionViewDelegate
#pragma mark - UICollectionViewDataSource



//多少张图片参与滚动
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    
    ShowImageCell *cell = (ShowImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:KCellIdentifier forIndexPath:indexPath];
    if (!cell) {
        return nil;
    }
    NSString *imageName = [NSString stringWithFormat:@"%ld.jpg",(long)indexPath.row];
    
    cell.imageView.image = [UIImage imageNamed:imageName ];
    cell.titleLabel.text = imageName;
    return cell;
    
    return cell;
}




#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)_scrollView
{
    //无限循环....
    float targetX = _scrollView.contentOffset.x;
    NSInteger numCount = [self.collect numberOfItemsInSection:0];
    float ITEM_WIDTH = _scrollView.frame.size.width;
    
    if (numCount>=3)
    {
        if (targetX < ITEM_WIDTH/2) {
            [_scrollView setContentOffset:CGPointMake(targetX+ITEM_WIDTH *numCount, 0)];
        }
        else if (targetX >ITEM_WIDTH/2+ITEM_WIDTH *numCount)
        {
            [_scrollView setContentOffset:CGPointMake(targetX-ITEM_WIDTH *numCount, 0)];
        }
    }
    
    
}





//collectionView的点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"asdasdasdasd");
}









- (void)SearchConnetion
{
    
    //滚动视图的网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://bapi.xinli001.com/fm2/hot_tag_list.json/?flag=4"] ;
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [bigDic objectForKey:@"data"];
        for (NSMutableDictionary *dic  in array) {
            Cover *model = [[Cover alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.coverArray addObject:model];
            
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
    //主播网络请求
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    NSString *str1 = [NSString stringWithFormat:@"http://bapi.xinli001.com/fm2/speaker_list.json/?v=1&key=c605710a2343f6da4ac22c8cce194bd0&rows=6&offset=0"];
    [manager1 GET:str1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       NSMutableArray *array1 = [bigDic1 objectForKey:@"data"];
        for (NSMutableDictionary *dic1  in array1) {
            Anchor *anchorModel = [[Anchor alloc]init];
            [anchorModel setValuesForKeysWithDictionary:dic1];
            [self.anchorArray addObject:anchorModel];
 
       }
    [self createAnchor];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}









//----------------------------------------------------------------------------------------------

#pragma mark - 创建searchBar

- (void)createSearchBar
{
    self.mySearch = [[UISearchBar alloc]initWithFrame:CGRectMake(0,  140 , [UIScreen mainScreen].bounds.size.width, 30)];
    [self.mySearch setBackgroundColor:[UIColor grayColor]];
    [self.mySearch setPlaceholder:@"输入心情或场景"];
    self.mySearch.delegate = self;
    self.mySearch.autocapitalizationType = UITextAutocorrectionTypeYes;
    self.mySearch.showsCancelButton = NO;
    [self.view addSubview:self.mySearch];
   // [self.mySearch setImage:[UIImage imageNamed:@"font-search.png"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    [self.mySearch release];
    
}


 
 - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    
    
    [self.mySearch  resignFirstResponder ];
    SearchByChooseViewController *search = [[SearchByChooseViewController alloc]init];
    [self.navigationController pushViewController:search animated:YES];
}

//-----------------------------------------------------------------------------------------------------------------------------------------------

#pragma mark - 创建scrollView
- (void)createScrollView
{
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 170, self.view.frame.size.width,self.view.frame.size.height - self.view.frame.size.width /  3 - 60)];
    [self.scroll setContentSize:CGSizeMake(0,1400)];
[self.scroll setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.scroll];
  
}


#pragma mark - 创建各种按钮
- (void)createGroupLable
{
    UILabel  *feeling = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, 30)];
    [feeling setText:@"心情"];
    [self.scroll addSubview:feeling];
    [feeling release];
    
    UILabel *scene = [[UILabel alloc]initWithFrame:CGRectMake(0, 380, self.view.frame.size.width, 30)];
    [scene setText:@"场景"];
    [self.scroll addSubview:scene];
    [scene release];
    
    UILabel *anchor = [[UILabel alloc]initWithFrame:CGRectMake(0, self.view.frame.size.width * 2 + 120, self.view.frame.size.width, 30)];
    [anchor setText: @"主播"];
    [self.scroll addSubview:anchor];
    [anchor release];
    
}


- (void)createMybutton
{
    for (int i = 0;  i < 18; i ++) {
        if (i < 9) {

        ChoiceButton * b = [[ChoiceButton alloc]initWithFrame:CGRectMake(i % 3 * (self.view.frame.size.width / 3), i / 3 * (self.view.frame.size.width / 3) + 50, (self.view.frame.size.width / 3), (self.view.frame.size.width / 3))];
            int a = i + 1;
            b.layer.borderWidth = 0.7;
           
            NSString *name = [NSString stringWithFormat:@"%d.png",a];
            [b.view setImage:[UIImage imageNamed:name]];
            
        
        
        [self.scroll addSubview:b];
            b.desc.text  = [self.choiceArray objectAtIndex:i];
            [b.desc  setFont:[UIFont systemFontOfSize:12]];
            [b.desc setTextAlignment:NSTextAlignmentCenter];
            [b.desc setTextColor:[UIColor blackColor]];

        b.tag = i + 1;
            b.desc  = [self.choiceArray objectAtIndex:i];
        [b  addTarget:self action:@selector(buttonAction: ) forControlEvents:UIControlEventTouchUpInside];
    [b release];
        }
        else
        {
            
            
            ChoiceButton * b = [[ChoiceButton alloc]initWithFrame:CGRectMake(i % 3 * (self.view.frame.size.width / 3), i / 3 * (self.view.frame.size.width / 3 ) + 100 , (self.view.frame.size.width / 3), (self.view.frame.size.width / 3))];
               int a = i + 1;
            b.layer.borderWidth = 0.7;


            NSString *name = [NSString stringWithFormat:@"%d.png",a];
            [b.view setImage:[UIImage imageNamed:name]];
            
            
            [self.scroll addSubview:b];
            b.tag = i + 1;
            b.desc.text  = [self.choiceArray objectAtIndex:i];
            [b.desc  setFont:[UIFont systemFontOfSize:12]];
            [b.desc setTextColor:[UIColor blackColor]];
              [b.desc setTextAlignment:NSTextAlignmentCenter];

            [b  addTarget:self action:@selector(buttonAction: ) forControlEvents:UIControlEventTouchUpInside];
            [b release];
        }
  
        
    }
    
}

- (void)buttonAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    NSLog(@"tag = %ld", button.tag);
    
   // NSLog(@"%@", [self.choiceArray objectAtIndex:(button.tag - 1)]);
    
    FeelingViewController *fell = [[FeelingViewController alloc]init];
    fell.choice = [self.choiceArray objectAtIndex:(button.tag - 1)];
    [self.navigationController  pushViewController:fell animated:YES];
}


// 写的主播按钮以及点击事件

- (void)createAnchor
{
    for (int i = 0;  i < 6;  i++) {
        AnchorBurron *anchor = [[AnchorBurron alloc]initWithFrame:CGRectMake(i % 2 * 160, i / 2 * 120 + self.view.frame.size.width * 2 + 150, 160 , 100)];
        [anchor addTarget:self action:@selector(AnchorAction:) forControlEvents:UIControlEventTouchUpInside];
        anchor.tag = i + 1;
        Anchor *anchorModel = [self.anchorArray objectAtIndex:i ];
        NSURL *url = [NSURL URLWithString:anchorModel.avatar];
       
        
        anchor.view.userInteractionEnabled = NO;
        anchor.view.clipsToBounds = YES;
        anchor.view.layer.cornerRadius = 30;
       [anchor.view sd_setImageWithURL:url placeholderImage:nil options:SDWebImageRetryFailed];
        anchor.Num.text = [NSString stringWithFormat:@"%ld",(long)anchorModel.fmnum];
        anchor.Num.font = [UIFont systemFontOfSize:15];
        [anchor.Num  setTextAlignment:NSTextAlignmentCenter];

        anchor.anchorName.text = anchorModel.username;
        
        anchor.anchorName.font = [UIFont systemFontOfSize:15];
       // [anchor.anchorName  setTextAlignment:NSTextAlignmentCenter];
        [self.scroll addSubview:anchor];
        [anchor release];
    }

}


- (void)AnchorAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSLog(@"tag =  %ld",button.tag );
  
    AnchorViewController *fell = [[AnchorViewController alloc]init];
    
    Anchor *model = [self.anchorArray objectAtIndex:button.tag - 1];
    
    fell.model = model;

    [self.navigationController  pushViewController:fell animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}






@end
